package practices;

import java.util.Arrays;
import java.util.List;
import java.util.Stack;

//判断一个后缀表达式是否合法
//能够对合法的后缀表达式进行计算
public class PostExpression {
    private PostExpression() {
    }
    final static double ERROR = -1;

    public static void main(String[] args) {
        System.out.println(eval("+ 1 2 3 4 + *".split("\\s+")));
        System.out.println(eval("5 1 5 / - 5 *".split("\\s+")));
    }

    //如果是一个后缀表达式不合法返回-1=ERROR,否则返回这个后缀式的值
    public static double eval(List<String> exp) {
        Stack<Double> S = new Stack<Double>();
        for (String tok : exp) {
            if (isNumber(tok)) {
                S.push(Double.parseDouble(tok));
            } else {
                if (S.size() < 2) return ERROR;
                double b = S.peek();
                S.pop();
                double a = S.peek();
                S.pop();
                double c = 0;
                switch (tok) {
                    case "+":
                        c = a + b;
                        break;
                    case "-":
                        c = a - b;
                        break;
                    case "*":
                        c = a * b;
                        break;
                    case "/":
                        if (b == 0) return ERROR;
                        c = a / b;
                        break;
                    default:
                        break;
                }
                S.push(c);
            }
        }
        return S.size() != 1 ? ERROR : S.peek();
    }

    public static double eval(String[] exp) {//委托
        return eval(Arrays.asList(exp));

    }

    public static boolean isNumber(String tok) {
        try {
            Double.parseDouble(tok);
            return true;

        } catch (NumberFormatException e) {
            return false;
        }
    }
}
